<?
$conf['graphviz'] = '/home/alangrafu/graphviz/bin/';
$conf['cmd'] = 'dot';

include_once('arc/ARC2.php');
error_reporting(E_ERROR);
header('Content-Type: text/plain');

$prefixes = array('pmlp:' => "http://inference-web.org/2.0/pml-provenance.owl#",
                  'pmlj:' => "http://inference-web.org/2.0/pml-justification.owl#",
                  'pmlt:' => "http://inference-web.org/2.0/pml-trust.owl#",
                  'ds:'   => "http://inference-web.org/2.0/ds.owl#",);

function validPML($u){
  //V=Have to figure it out how to validate it
  return true;
}

function noNamespace($t){
  global $prefixes;
  foreach($prefixes as $k => $v){
    if(strpos($t, $v) === 0){
      return preg_replace("|^".str_replace('|', '\|', $v)."|", $k, $t, 1);
    }
  }
  return $t;
}


function getPosition($c, $m, $d){
  $r = array();
  $r['x'] = 500+2*rand(-1*$d*($c -$m), $d*($c -$m));
  $r['y'] = ($d*$c - $m)+rand(-1*$d/2, $d/2)+rand(-50, 50);
  return $r;
}

function getLayout($t){
  global $conf;
  $prefix = 'ZXC';
  $h;
  $graph = 'digraph {
  ';
  foreach($t as $v){
     $aux1 = $prefix.md5($prefix.$v['s']);
     $h[$aux1] = $v['s'];
     $aux2 = $prefix.md5($prefix.$v['o']);
     $h[$aux2] = $v['o'];
     $graph .= $aux1." -> ".$aux2."\n";
  }
  $graph .= "}";
  //echo $graph;
  $command = "echo '".$graph."' | ".$conf['graphviz'].$conf['cmd']." -y -Tplain ";
  $a = shell_exec($command);
  $b = explode("\n", $a);
  $result;
  $gwidth=1;
  $gheight=1;
  $c = preg_grep("/^graph/", $b);
  foreach($c as $v){
    $aux = explode(" ", trim($v));
    $gwidth = $aux[2];
    $gheight = $aux[3];
  }
  $c = preg_grep("/^node/", $b);
  foreach($c as $v){
    $aux = explode(" ", $v);
    $lwidth = 1000*(($aux[2]+0)/$gwidth);
    $lheight = 1000*(($aux[3]+0)/$gheight);
    $result[$h[$aux[1]]]['x'] = round($lwidth);
    $result[$h[$aux[1]]]['y'] = round((1+ rand(-100,100)/400)*$lheight);
  }
  return $result;
}
function getMinValue($arr){
  $min = INF;
  $name = "";
  foreach($arr as $k => $v){
    if($min > $v){
      $min = $v;
      $name = $k;
    }
  }
  return $name;
}

function BFS($start, $adj, $weight, $baseheight){
  //Init
  $step = 1;
  $w = $weight;
  $stack = array();
  array_push($stack, $start);
  $results = array();
  $results[$start]['x'] = $w/2;
  $results[$start]['y'] = $baseheight;
  $checked = array();
  //Loop
  while(count($stack)>0){
    $step++;
    $x = array_pop($stack);
    if(isset($adj[$x])){
      $xarr = $adj[$x];
      foreach($xarr as $k => $v){
        if(!isset($checked[$v])){
          if(count($xarr)>1){
            $results[$v]['x'] = 20+floor(0+$results[$x]['x'] + ($w/(count($xarr)-1)*$k - $w/2));
          }else{
            $results[$v]['x'] = 20+floor(0+$results[$x]['x']);
          }
          $results[$v]['y'] = floor(0+$results[$x]['y']  + ($step*$baseheight)) + rand(-1*$baseheight/3, $baseheight/3);
          $checked[$v] = true;
          array_push($stack, $v);
        }
      }
    }
  }
  return $results;
}

function getTypeString($u){
  if($u == "uri"){
    return "resource";
  }elseif($u == "bnode"){
    return "blank";
  }elseif($u == "literal"){
    return "literal";
  }
  return null;
}

if(!isset($_GET['uri'])){
  exit(0);
}


$u =$_GET['uri'];

$c = file_get_contents($u);
if (is_bool($c) && $c == false)
{
  print '{ "status": "ERROR"}';
  exit(0);
}
$existing = array();
$jsonobj = array();
$types = array();
$positions = array();
$counter = array();
$max = 0;
$distancestep = 100;
$adjacency =  array();
$pointedto = array();

if(validPML($u)){
  
  $pmlp ='http://inference-web.org/2.0/pml-provenance.owl#';
  $parser = ARC2::getRDFParser();
  $parser->parse($pmlp, $c);
  $triples = $parser->getTriples();
  //print_r($triples);  
  //echo $c;
  
  foreach($triples as $k => $v){
    if($v['p'] == 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'){
      $types[$v['s']] = $v['o'];
    }else{
      $counter[$v['s']]++;
      $counter[$v['o']]++;
      if($max < $counter[$v['s']]){
        $max = $counter[$v['s']];
      }
      if($max < $counter[$v['o']]){
        $max = $counter[$v['o']];
      }
      if(!isset($adjacency[$v['s']])){
        $adjacency[$v['s']] = array();
      }
      
      array_push($adjacency[$v['s']], $v['o']);
      $pointedto[$v['o']]++;
      $pointedto[$v['s']] += 0;
    }
  }
  
  //$pos = BFS(getMinValue($pointedto), $adjacency, 0.8*(0+ $_GET['w']), 50);
  $pos = getLayout($triples);
  //print getMinValue($pointedto)." ".$adjacency." ".(0+ $_GET['w']);
  //print_r($pos);
  //exit(0);
  foreach($triples as $k => $v){
    if($v['p'] == 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'){
      continue;
    }
    
    if(!isset($existing[$v['s']])){
      $index = array();
      $index['type'] = getTypeString($v['s_type']);
      if(isset($types[$v['s']])){
        $index['rdftype'] = $types[$v['s']];
      }else{
        $index['rdftype'] = ""; //$v['s'];
      }
      $index['resource']['element']['name'] = $v['s'];
      $index['resource']['element']['namespace']['prefix'] = "";
      $index['resource']['element']['namespace']['uri'] = $v['s'];
      //$pos = getPosition($counter[$v['s']], $max, $distancestep);
      $index['resource']['shape']['bbox']['x'] = $pos[$v['s']]['x'];
      $index['resource']['shape']['bbox']['y'] = $pos[$v['s']]['y'];
      $index['resource']['shape']['bbox']['width'] = 225;
      $index['resource']['shape']['bbox']['height'] = 20;
      $index['resource']['shape']['uuid'] = uniqid();
      $existing[$v['s']] = $index['resource']['shape']['uuid'];
      $positions[$v['s']]['x'] = $pos[$v['s']]['x']; //$index['resource']['shape']['bbox']['x'];
      $positions[$v['s']]['y'] = $pos[$v['s']]['y']; //$index['resource']['shape']['bbox']['y'];
      
      array_push($jsonobj, $index);
    }
    
    
    if(!isset($existing[$v['o']])){
      $index = array();
      $index['type'] = getTypeString($v['o_type']);
      
      if($index['type'] != 'literal'){
        if(isset($types[$v['o']])){
          $index['rdftype'] = $types[$v['o']];
        }else{
          $index['rdftype'] = "";//$v['o'];
        }      
        $index['resource']['element']['name'] = $v['o'];
        $index['resource']['element']['namespace']['prefix'] = "";
        $index['resource']['element']['namespace']['uri'] = $v['o'];
        //$pos = getPosition($counter[$v['o']], $max, $distancestep);
        $index['resource']['shape']['bbox']['x'] = $pos[$v['o']]['x'];
        $index['resource']['shape']['bbox']['y'] = $pos[$v['o']]['y'];
        $index['resource']['shape']['bbox']['width'] = 225;
        $index['resource']['shape']['bbox']['height'] = 20;
        $index['resource']['shape']['uuid'] = uniqid();
        $existing[$v['o']] = $index['resource']['shape']['uuid'];
        $positions[$v['o']]['x'] = $pos[$v['o']]['x']; //$index['resource']['shape']['bbox']['x'];
        $positions[$v['o']]['y'] = $pos[$v['o']]['y']; //$index['resource']['shape']['bbox']['y'];
        
      }else{
        $index['text'] = $v['o'];
        $index['lang'] = $v['o_lang'];
        $index['datatype'] = $v['o_datatype'];
        //$pos = getPosition($counter[$v['o']], $max, $distancestep);
        $index['shape']['bbox']['x'] = $pos[$v['o']]['x'];
        $index['shape']['bbox']['y'] = $pos[$v['o']]['y'];
        $index['shape']['bbox']['width'] = 225;
        $index['shape']['bbox']['height'] = 20;
        $index['shape']['uuid'] = uniqid();
        $existing[$v['o']] = $index['shape']['uuid'];
        $positions[$v['o']]['x'] = $pos[$v['o']]['x']; //$index['shape']['bbox']['x'];
        $positions[$v['o']]['y'] = $pos[$v['o']]['y']; //$index['shape']['bbox']['y'];
      }
      
      
      array_push($jsonobj, $index);
    }
    
    {//Predicates
      $index = array();
      $index['type'] = 'property';
      $index['uuidIni'] = $existing[$v['s']];
      $index['uuidEnd'] = $existing[$v['o']];
      $index['resource']['element']['name'] = noNamespace($v['p']);
      $index['resource']['element']['namespace']['prefix'] = "";
      $index['resource']['element']['namespace']['uri'] = ($v['p']);
      $index['resource']['shape']['bbox']["x"]=round(($pos[$v['o']]['x'] + $pos[$v['s']]['x'])/2);
      $index['resource']['shape']['bbox']["y"]=round(($pos[$v['o']]['y'] + $pos[$v['s']]['y'])/2);
      $index['resource']['shape']['bbox']["width"]=145;
      $index['resource']['shape']['bbox']["height"]=20;
      $index['resource']['shape']['uuid'] = uniqid();
      
      array_push($jsonobj, $index);
    }
    
  }
  //print_r($pos);
  
}
//print_r($jsonobj);
echo str_replace("\/", "/", json_encode($jsonobj));
//echo $c;
?>
